/*
*   @Author: 1296
*   @Date: 2025-05-05
*   @Description: 签到记录
*/

<template>
  <div class="attendance-container">
    <div class="activity-list">
      <h2>签到活动记录</h2>
      <el-table :data="activityList" style="width: 100%; font-size: 12px" @row-click="handleActivityClick">
        <el-table-column prop="title" label="活动标题"></el-table-column>
        <el-table-column prop="courseName" label="课程名称"></el-table-column>
        <el-table-column prop="sysClassName" label="班级"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column prop="endTime" label="结束时间"></el-table-column>
        <el-table-column prop="type" label="签到类型" :formatter="formatType"></el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <div>
              <el-button
                  v-if="!isActivityEnded(scope.row.endTime)"
                  type="primary"
                  @click.stop="handleShowActivityDetails(scope.row.id, scope.row.type)"
                  :disabled="isEndingActivityDisabled(scope.row.id)"
                  size="small"
              >
                查看详情
              </el-button>
              <el-button
                  v-if="!isActivityEnded(scope.row.endTime)"
                  type="danger"
                  @click.stop="handleEndActivity(scope.row.id)"
                  :disabled="isEndingActivityDisabled(scope.row.id)"
                  size="small"
              >
                结束活动
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="totalActivities"
          layout="prev, pager, next"
          @current-change="handlePageChange"
      ></el-pagination>
    </div>

    <!-- 学生签到情况对话框 -->
    <el-dialog
        v-model="showRecordDetails"
        width="80%"
        @close="handleCloseDialog"
        append-to-body
    >
      <template #header>
        <h2>学生签到情况</h2>
      </template>
      <StudentAttendance
          :aid="selectedActivityId"
          :recordPageSize="recordPageSize"
          @update:recordPage="handleRecordPageChange"
      />
    </el-dialog>

    <!-- 签到详情对话框 -->
<!--    <el-dialog-->
<!--        v-model="showActivityDetailsDialog"-->
<!--        width="60%"-->
<!--        @close="handleCloseActivityDetailsDialog"-->
<!--        append-to-body-->
<!--    >-->
<!--      <template #header>-->
<!--        <h2>签到详情</h2>-->
<!--      </template>-->
<!--      <div v-if="activityDetails">-->
<!--        <p v-if="activityDetails.locationDto">-->
<!--          签到位置：{{ activityDetails.locationDto.latitude }}, {{ activityDetails.locationDto.longitude }}-->
<!--          <br>-->
<!--          范围：{{ activityDetails.locationDto.range }} 米-->
<!--        </p>-->
<!--        <p v-if="activityDetails.qrcode">-->
<!--          二维码：{{ activityDetails.qrcode }}-->
<!--        </p>-->
<!--        <p v-if="activityDetails.gesture">-->
<!--          手势：{{ activityDetails.gesture.join(' -> ') }}-->
<!--        </p>-->
<!--        <p v-if="activityDetails.code">-->
<!--          签到码：{{ activityDetails.code }}-->
<!--        </p>-->
<!--      </div>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import StudentAttendance from './StudentAttendance.vue';
import store from "@/store";

const api = axios.create({
  baseURL: store.getters.getBaseURL
});

// 请求和响应拦截器
api.interceptors.request.use(config => {
  const token = sessionStorage.getItem('userToken');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

api.interceptors.response.use(
    response => response,
    error => {
      if (error.response?.status === 401) {
        window.location.href = '/loginAndRegister';
      }
      return Promise.reject(error);
    }
);

export default {
  components: {
    StudentAttendance
  },
  data() {
    return {
      activityList: [],
      currentPage: 1,
      pageSize: 8,
      totalActivities: 0,
      showRecordDetails: false,
      selectedActivityId: null,
      recordPage: 1,
      recordPageSize: 5,
      totalRecords: 0,
      endActivityDisabled: {}
      // showActivityDetailsDialog: false, // 控制签到详情对话框的显示
      // activityDetails: null, // 存储签到详情信息
    };
  },
  created() {
    this.getActivityList();
  },
  methods: {
    // 获取签到活动列表
    getActivityList() {
      api
          .get(`/activity/list?pageNo=${this.currentPage}&pageSize=${this.pageSize}`)
          .then(response => {
            if (response.data.status === 'success') {
              this.activityList = response.data.data.list;
              this.totalActivities = response.data.data.resultCount;
            } else {
              ElMessage.error(response.data.info || '获取签到活动失败');
            }
          })
          .catch(error => {
            console.error('Error fetching activity list:', error);
            ElMessage.error('获取签到活动失败');
          });
    },
    // 处理活动列表点击事件
    handleActivityClick(row) {
      this.selectedActivityId = row.id;
      this.$nextTick(() => {
        this.showRecordDetails = true;
      });
      this.recordPage = 1; // 重置分页
    },
    // 处理活动列表分页变化
    handlePageChange(page) {
      this.currentPage = page;
      this.getActivityList();
    },
    // 处理签到记录分页变化
    handleRecordPageChange(page) {
      this.recordPage = page;
    },
    // 处理对话框关闭事件
    handleCloseDialog() {
      this.showRecordDetails = false;
      this.$nextTick(() => {
        this.selectedActivityId = null;
        this.recordPage = 1;
      });
    },
    // 判断活动是否结束
    isActivityEnded(endTime) {
      const now = new Date();
      const activityEnd = new Date(endTime);
      return now >= activityEnd; // 如果当前时间大于或等于结束时间，则认为活动已结束
    },
    // 处理结束活动的方法
    handleEndActivity(aid) {
      this.endActivityDisabled[aid] = true;
      api
          .get(`/activity/quit/${aid}`)
          .then(response => {
            if (response.data.status === 'success') {
              ElMessage.success('活动已成功结束');
              this.getActivityList(); // 刷新活动列表
            } else {
              ElMessage.error(response.data.info || '结束活动失败');
              this.endActivityDisabled[aid] = false;
            }
          })
          .catch(error => {
            console.error('Error ending activity:', error);
            ElMessage.error('结束活动失败');
            this.endActivityDisabled[aid] = false;
          });
    },
    // 判断结束活动按钮是否禁用
    isEndingActivityDisabled(aid) {
      return this.endActivityDisabled[aid] || false; // 判断是否禁用按钮
    },
    // 格式化签到类型
    formatType(row, column, cellValue) {
      switch (cellValue) {
        case '0':
          return '普通签到'
        case '1':
          return '手势签到'
        case '2':
          return '位置签到'
        case '3':
          return '二维码签到'
        case '4':
          return '签到码签到'
        default:
          return cellValue
      }
    },
    // 处理“查看详情”按钮点击事件
    handleShowActivityDetails(aid, type) {
      const jobCode = sessionStorage.getItem('jobCode');
      this.$router.push(`/${jobCode}/recordDetail?aid=${aid}&type=${type}`);
    },
    // 获取签到活动详情
    // getActivityDetails(aid, type) {
    //   api
    //       .get(`/activity/additionInfo/${aid}/${type}`)
    //       .then(response => {
    //         if (response.data.status === 'success') {
    //           this.activityDetails = response.data.data;
    //           console.log('签到详情信息：', JSON.stringify(this.activityDetails));
    //         } else {
    //           ElMessage.error(response.data.info || '获取签到详情失败');
    //         }
    //       })
    //       .catch(error => {
    //         console.error('Error fetching activity details:', error);
    //         ElMessage.error('获取签到详情失败');
    //       });
    // },
    // 处理签到详情对话框关闭事件
    // handleCloseActivityDetailsDialog() {
    //   this.showActivityDetailsDialog = false;
    //   this.activityDetails = null;
    // },
  }
};
</script>

<style scoped>
.attendance-container {
  padding: 20px;
}

.activity-list {
  margin-bottom: 20px;
}

h2 {
  margin-bottom: 15px;
  color: #333;
}

.el-pagination {
  margin-top: 15px;
  text-align: center;
}

</style>